import kinterbasdb; kinterbasdb.init(type_conv=200)
import MSLogger
import PCNDBMethods
from time import sleep
import pdb

class Writer:
    def __init__(self, DBPath, DBUser, DBPass):
        self.dbPath = DBPath
        self.dbUser = DBUser
        self.dbPass = DBPass
        self.connection = None

    def connect(self):
        attemptCount = 0
        self.connection = None
        while True:
            try:
                self.connection = kinterbasdb.connect(dsn=self.dbPath,
                                                      user=self.dbUser,
                                                      password=self.dbPass)
                break
            except:
                secs = 2
                attemptCount += 1
                if attemptCount > 3:
                    attemptCount = 0
                    secs *= 10
                MSLogger.logWarn('Connection failed to PCN FB(%s@%s). Sleep %d secs before new attempt' % (self.dbPath, self.dbUser, secs))
                sleep(secs)
                continue
        return True

    def ensureConnection(self):
        if self.connection == None or self.connection.closed:
            self.connect()
            MSLogger.logDebug('Connected to PCN FB')
        return True

    def writeEvents_Static(self, MSObjects):
        self.ensureConnection()
        dbCursor = self.connection.cursor()
        recId    = PCNDBMethods.GET_LastRecId_FROM_sgn(dbCursor)
        for obj in MSObjects:
            try:
                #pdb.set_trace()
                canClearEvents = True
                obj.eventsPGSM.sort()
                MSLogger.logInfo('Writer: Static: object(%s/%s) processing %d PGSM events' % (str(obj.objectMSId), str(obj.objectPCNId), len(obj.eventsPGSM)))
                for e in obj.eventsPGSM:
                    try:
                        e.userWriterId = str(self.dbUser)
                        recId = PCNDBMethods.STORE_MSEvent_TO_sgn(dbCursor, e, recId)
                    except Exception, err:
                        MSLogger.logError('Writer: Static: event processing failed: error(%s)' % (str(err)))
                        canClearEvents = False
                        continue
                if canClearEvents:
                    obj.eventsPGSM = []

                canClearEvents = True
                obj.eventsContactId.sort()
                MSLogger.logInfo('Writer: Static: object(%s/%s) processing %d contactId events' % (str(obj.objectMSId), str(obj.objectPCNId), len(obj.eventsContactId)))
                for e in obj.eventsContactId:
                    try:
                        e.userWriterId = str(self.dbUser)
                        recId = PCNDBMethods.STORE_MSEvent_TO_sgn(dbCursor, e, recId)
                    except Exception, err:
                        MSLogger.logError('Writer: Static: event processing failed: error(%s)' % (str(err)))
                        canClearEvents = False
                        continue
                if canClearEvents:
                    obj.eventsContactId = []

            except Exception, err:
                MSLogger.logError('Writer: Static: object processing failed: error(%s)' % (str(err)))
                continue
        self.connection.commit()
        return